const axios = require('axios');
const iconv = require('iconv-lite');
const cheerio = require('cheerio');
const {heros} = require('./heros');
const download = require('download');
const fs = require('fs');

// axios({
//     url: 'https://pvp.qq.com/web201605/herodetail/538.shtml',
//     responseType: "arraybuffer" 
// }).then(response => {
//     var strJson = iconv.decode(response.data, 'gbk');

//     const $ = cheerio.load(strJson);

//     console.log($('.pop-bd').html());
// })

~async function(){
    for(let i=0;i<heros.length;i++){
        //初始化 skills
        heros[i].skills = [];

        let response = await axios({
            url: heros[i].remote_url,
            responseType: "arraybuffer" 
        })

        var strJson = iconv.decode(response.data, 'gbk');
        
        const $ = cheerio.load(strJson);
        //获取介绍
        heros[i].intro = $('.pop-bd').html()
        //获取技能 {skill: [{name:'x', img: 'xxx.jpg'}      ]}
        $('.skill-u1 li').each((index,v) => {
            let obj = {};
            //设置技能名称
            obj.name = $('.skill-show .skill-name b').eq(index).html();
            if(!obj.name) return;
            //获取图片
            obj.img = $('.skill-u1 li img').eq(index).attr('src');
            //下载图片
            let dir = __dirname + '/../public/images/heros/skills'
            let url = 'http:'+obj.img;
            let name = obj.img.split('/').pop()
            //下载图片
            let path = dir + '/'+ name;
            //设置 img
            download(url).pipe(fs.createWriteStream(path));
            obj.img = '/images/heros/skills/'+name;
            //将对象压入技能数组
            heros[i].skills.push(obj);
        })

    }

    let obj = {heros};
    require('fs').writeFileSync(__dirname +'/test2.json', JSON.stringify(obj));
}()
